package org.skf.common.log

import android.annotation.SuppressLint
import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import android.os.Message
import java.io.File
import java.io.FileOutputStream
import java.io.FileWriter
import java.text.SimpleDateFormat
import java.util.*
import java.util.zip.ZipOutputStream

lateinit var logDir: String
private const val save = 0xa
private const val maxLength = 10 * 1024 * 1024

/**
 * 存储日志线程
 */
object SaveLogThread : HandlerThread("SaveLog") {

    lateinit var handler: Handler
        private set
    var caller: (() -> Unit)? = null

    override fun onLooperPrepared() {
        super.onLooperPrepared()
        handler = SaveLogHandler(looper) {
            (it.what == save).apply {
                handler.sendEmptyMessageDelayed(save, period)
            }
            false
        }
        caller?.invoke()
        handler.sendEmptyMessageDelayed(save, period)
    }

    fun launch(caller: () -> Unit) {
        this.caller = caller
        if (state != State.NEW) {
            caller.invoke()
            return
        }
        super.start()
    }
}

private const val period: Long = 2 * 1000

/**
 * 存储日志线程handler
 * 每隔[period]时间保存一次日志,还可能丢失至多[period]的日志
 */
class SaveLogHandler(looper: Looper, callback: Callback) : Handler(looper, callback) {
    private val record = mutableListOf<String>()
    override fun handleMessage(msg: Message) {
        super.handleMessage(msg)
        if (msg.what == save) {
            saveRecord2Disk(record)
        } else {
            val s = msg.obj as String
            record.add(s)
        }
    }
}

/**
 * 保存到磁盘
 */
private fun saveRecord2Disk(content: MutableList<String>) {
    if (content.isEmpty()) return
    val dest = generateFile()
    FileWriter(dest,true).use {
        for (s in content) {
            it.append(s)
        }
    }
    content.clear()
}

/**
 * 获取写入文件
 */
fun generateFile(): File {
    val parentDir = File(logDir)
    if (!parentDir.exists()) {
        throw RuntimeException("no logs dir")
    }
    val logs = parentDir.listFiles()
    val last = logs?.lastOrNull()

    if (last != null) {
        return if (last.length() >= maxLength) {
            File(logDir, "${timeStamp()}.log")
        } else {
            last
        }
    }
    return File(logDir, "${timeStamp()}.log")
}

/**
 * 根据当前timeStamp生成时间(年月日时分秒)
 */
@SuppressLint("ConstantLocale")
private val dateFmt = SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault())
private val date = Date()
private fun timeStamp(): String {
    date.time = System.currentTimeMillis()
    return dateFmt.format(date)
}

/**
 * 文件压缩
 */
private fun zipFile(src:File){
    val dest = src.absolutePath.replaceAfterLast(".", "zip")
    val zipOutputStream =
        ZipOutputStream(FileOutputStream(dest))
}